/*
* Copyright (C) Microsoft. All rights reserved.  
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not 
* use this file except in compliance with the License.  You may obtain a copy 
* of the License at http://www.apache.org/licenses/LICENSE-2.0  
* 
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 
* WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
* MERCHANTABLITY OR NON-INFRINGEMENT. 
*
* See the Apache License, Version 2.0 for specific language governing 
* permissions and limitations under the License.
*
*/
#pragma once

#include <baja/common.hpp>
#include <baja/testable.hpp>

#include <Windows.h>

namespace baja { namespace win32 { namespace details {

class safe_handle : public testable_base
{
public:
    explicit safe_handle() : _handle(INVALID_HANDLE_VALUE) {}
    explicit safe_handle(const HANDLE handle) : _handle(handle) {}
    ~safe_handle()
    {
        if (this->isValid())
        {
            BAJA_TESTABLE_EVENT("close_handle", &_handle);
            CloseHandle(_handle);
        }
    }
    explicit safe_handle(safe_handle&& other)
    {
        this->transferFrom(other);
    }

    safe_handle& operator=(safe_handle&& other)
    {
        this->transferFrom(other);
        return *this;
    }

    bool isValid() { return (_handle != NULL) && (_handle != INVALID_HANDLE_VALUE); }

    const HANDLE get() { return _handle; }

    void transferFrom(safe_handle& other)
    {
        // transfer ownership
        if (this->isValid())
        {
            CloseHandle(_handle);
        }
        _handle = other._handle;
        other._handle = INVALID_HANDLE_VALUE;
    }

#ifdef BAJA_CONFIG_TEST_BUILD
    void* inspectInternal(const std::string& iid)
    {
        if (iid.compare("handle") == 0) // _handle
        {
            return &_handle;
        }
        return testable_base::inspectInternal(iid);
    }
#endif // BAJA_CONFIG_TEST_BUILD

private:

    // disable copy
    safe_handle(const safe_handle& other) {}
    safe_handle& operator=(const safe_handle& other) { return *this; }

    HANDLE _handle;
};

}}} // namespace baja.win32.details